package com.zhou.base.components.bs.common.mybatishandler;

import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xianfeng
 * @date 2023/7/28 15:34
 * @description:
 */
public class ListLongTypeHandler extends BaseTypeHandler<List<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Long> list, JdbcType jt) throws SQLException {
        ps.setString(i, StrUtil.join(",", list));
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (value == null) {
            return null;
        }
        String[] split = value.split(",");
        List<Long> collect = Arrays.asList(split).stream().map(t -> Long.parseLong(t)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        String[] split = value.split(",");
        List<Long> collect = Arrays.asList(split).stream().map(t -> Long.parseLong(t)).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        String[] split = value.split(",");
        List<Long> collect = Arrays.asList(split).stream().map(t -> Long.parseLong(t)).collect(Collectors.toList());
        return collect;
    }
}
